package com.yueke.gemini.utils;


import com.bizvane.sun.common.utils.MD5Util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


/**
 * Created by iBo on 16/3/30.
 */

/**
 * AES 加解密
 */
public class AESUtil {


	private static byte[] Encrypt(byte[] text, byte[] key) throws Exception {
		SecretKeySpec aesKey = new SecretKeySpec(key, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, aesKey);
		return cipher.doFinal(text);
	}

	private static byte[] Decrypt(byte[] text, byte[] key) throws Exception {
		SecretKeySpec aesKey = new SecretKeySpec(key, "AES");

		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, aesKey);
		return cipher.doFinal(text);
	}

	public static String EncodeAES(String text, String key) throws Exception{
		byte[] keybBytes = MD5Util.getMD5Byte16(key);
		byte[] textBytes = text.getBytes();
		byte[] aesBytyes = Encrypt(textBytes, keybBytes);
		return new String(Base64Util.encode(aesBytyes));
	}

	public static String DeCodeAES(String text, String key) throws Exception{
		byte[] keybBytes = MD5Util.getMD5Byte16(key);
		byte[] debase64Bytes = Base64Util.decode(text);
		return new String(Decrypt(debase64Bytes, keybBytes));
	}
}

